package com.wondersgroup.util;

import javax.servlet.http.HttpServletRequest;

public class HttpServletRequestUtil {
  /**
   *  转换 成 Int 类型
   * @param request
   * @param key
   * @return
   */
  public static int  getInt(HttpServletRequest request, String key){
    try{
      return  Integer.decode(request.getParameter(key));
    }catch (Exception e) {
      return -1;
    }
  }
  /**
   *  转换 成 double 类型
   * @param request
   * @param key
   * @return
   */
  public static double getDouble(HttpServletRequest request, String key){
    try{
      return  Double.valueOf(request.getParameter(key));
    }catch (Exception e) {
      return -1d;
    }
  }
  /**
   *  转换 成 long 类型
   * @param request
   * @param key
   * @return
   */
  public static Long getLong(HttpServletRequest request, String key){
    try{
      return  Long.valueOf(request.getParameter(key));
    }catch (Exception e) {
      return -1L;
    }
  }
  /**
   *  转换 成 boolean 类型
   * @param request
   * @param key
   * @return
   */
  public static boolean getBoolean(HttpServletRequest request, String key){
    try{
      return  Boolean.valueOf(request.getParameter(key));
    }catch (Exception e) {
      return false;
    }
  }

  /**
   *  转换 成  String  类型
   * @param request
   * @param key
   * @return
   */
  public static String  getString(HttpServletRequest request, String key){
    try{
      String result =  request.getParameter(key);
      if(result != null ){
        result = result.trim();
      }
      if("".equals(result)){
        result = null;
      }
      return result;
    }catch (Exception e) {
      return null;
    }
  }
  public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

}
